package com.dyz.wsw.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.Collections;

/**
 * 跨域配置
 * @author dyz
 * Time 2024/6/8 0:19
 */
@Configuration
public class CorsConfig {

    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)//确保在其他过滤器前生效,否则自定义的一些Filter会有跨域问题
    public CorsWebFilter corsWebFilter(){
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Collections.singletonList("*")); // 允许所有来源，或者指定特定来源
        config.setAllowedMethods(Collections.singletonList("*")); // 允许所有请求方法
        config.setAllowedHeaders(Collections.singletonList("*")); // 允许所有请求头
        config.setMaxAge(3600L); // 预检请求的有效期，单位为秒

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 对所有路径应用CORS配置

        return new CorsWebFilter(source);
    }
}
